﻿using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

namespace SmarterCharger.Library.Infrastructure
{
    internal class BasicAuthenticationHttpClient : HttpClient
    {
        private readonly string _username;
        private readonly string _password;
        
        public BasicAuthenticationHttpClient(string username, string password)
        {
            if (string.IsNullOrWhiteSpace(username)) throw new ArgumentNullException("username");
            if (string.IsNullOrWhiteSpace(password)) throw new ArgumentNullException("password");

            _username = username;
            _password = password;

            DefaultRequestHeaders.Authorization = CreateBasicAuthenticationHeader(username, password);
        }

        private AuthenticationHeaderValue CreateBasicAuthenticationHeader(string username, string password)
        {
            var encodedCredentials = EncodeCredentials(username, password);

            return new AuthenticationHeaderValue("Basic", encodedCredentials);
        }

        private string EncodeCredentials(string username, string password)
        {
            var credentials = string.Format("{0}:{1}", username, password);
            var encodedCredentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials));

            return encodedCredentials;
        }
    }
}
